package com.jxf.demo.service.impl;

import com.jxf.demo.dto.DXFPointInfo;
import com.jxf.demo.dto.Rectangle;
import com.jxf.demo.dto.StraightLine;
import com.jxf.demo.service.AbstractDXFParseService;
import org.kabeja.dxf.DXFLWPolyline;
import org.kabeja.dxf.helpers.Point;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DXFPolyLineParseService extends AbstractDXFParseService {
    @Override
    public List<DXFPointInfo> doParse(List lineEntities) {
        return parsePolyLine(lineEntities);
    }

    @Override
    public String getType() {
        return "LWPOLYLINE";
    }

    /**
     * 多边形
     *
     * @param lineEntities
     */
    public List<DXFPointInfo> parsePolyLine(List lineEntities) {
        List<DXFPointInfo> list = new ArrayList<>();
        // 多段线(矩形、多边矩形等)
        // 每个line为一个图形
        for (Object lineEntity : lineEntities) {
            DXFLWPolyline polyLine = (DXFLWPolyline) lineEntity;
            // 遍历每个顶点
            List<StraightLine> points = new ArrayList<>();
            int vertexCount = polyLine.getVertexCount();
            for (int i = 0; i < vertexCount; i++) {
                int next = i + 1;
                // 最后一个顶点的终点坐标为第一个顶点的起点坐标
                next = next == vertexCount ? 0 : next;
                // 当前顶点的起点坐标
                Point startPoint = polyLine.getVertex(i).getPoint();
                // 下一个顶点的起点坐标为当前顶点的起点坐标
                Point endPoint = polyLine.getVertex(next).getPoint();

//                DXFPointInfo.PointDetail linePoint = new DXFPointInfo.PointDetail();
                StraightLine line = new StraightLine();
                // 起点坐标
                StraightLine.Coordinate start = StraightLine.Coordinate.getPointCoordinate(startPoint.getX(), startPoint.getY());
                StraightLine.Coordinate end = StraightLine.Coordinate.getPointCoordinate(endPoint.getX(), endPoint.getY());
//                终点坐标
//                Point end = new Point();
//                end.setX(endPoint.getX());
//                end.setY(endPoint.getY());
//                end.setZ(endPoint.getZ());
                line.setStart(start);
                line.setEnd(end);

                points.add(line);
            }
            // 根据坐标计算外接矩形的长宽
            List<BigDecimal> pointXList = points.stream().map(point -> point.getStart().getX()).collect(Collectors.toList());
            List<BigDecimal> pointYList = points.stream().map(point -> point.getStart().getY()).collect(Collectors.toList());
            Rectangle rectangle = super.getRectangle(pointXList, pointYList);
            DXFPointInfo dxfPoint = DXFPointInfo.builder()
                    .type(getType())
                    .points(points)
                    .rectangle(rectangle).build();
            list.add(dxfPoint);
        }
        return list;
    }
}
